<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clearList"
    >
      <template v-if="meta.indexOf('CourseOrderExp') > -1" #btns>
        <el-button :loading="subLoading" type="primary" @click="handleExport">导出</el-button>
      </template>
    </QueryForm>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-tableb"
    >
      <el-table-column
        align="center"
        label="订单编号"
        min-width="220"
        show-overflow-tooltip
        prop="orderId"
      >
        <template v-slot="scope">
          <span class="ckxqBtn" @click="handleDetail(scope.row)">{{
            scope.row.orderId
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="会员信息"
        min-width="250"
        prop="memberInfo"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="课程名称"
        min-width="140"
        prop="courseName"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="课程类型"
        prop="payMethod"
        min-width="120"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-if="scope.row.flag == '1'">视频课</span>
          <template v-if="scope.row.flag == '2'">
            <span v-if="scope.row.courseType == '1'">常规课</span>
            <span v-if="scope.row.courseType == '3'">常规课</span>
            <span v-if="scope.row.courseType == '4'">私教课</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="课程价格(元)"
        prop="price"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="支付方式"
        prop="payMethod"
        min-width="120"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.payMethodName }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="实付金额"
        prop="allPrice"
        min-width="100"
      />
      <el-table-column
        align="center"
        label="已退款金额"
        prop="refundPrice"
        min-width="100"
      />
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        min-width="160"
      />
      <el-table-column
        align="center"
        label="支付时间"
        prop="payTime"
        min-width="160"
      />
      <el-table-column
        align="center"
        label="订单来源"
        prop="channel"
        min-width="100"
      />
      <el-table-column
        align="center"
        label="备注"
        prop="note"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="操作人"
        prop="orderOperator"
        min-width="120"
      />
      <el-table-column
        align="center"
        label="订单状态"
        prop="orderStatus"
        min-width="100"
        fixed="right"
      >
        <template slot-scope="scope">
          {{
            scope.row.statusName
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="scope.row.orderStatus == 3 && meta.indexOf('OfflinecoursesOrderRefund') > -1"
              v-preventReClick
              type="text"
              @click="rowClickRefound(scope.row)"
            >取消订单</el-button>
            <el-button
              v-if="
                scope.row.orderStatus == 3 &&
                  meta.indexOf('CoursePrinterOrder') > -1
              "
              v-preventReClick
              type="text"
              @click="rowPrint(scope.row.orderId)"
            >打印小票</el-button>
            <el-button
              v-if="scope.row.orderStatus == 0 && meta.indexOf('CourseContinuePay') > -1"
              v-preventReClick
              type="text"
              @click="rowClickGoOn(scope.row)"
            >继续支付</el-button>
            <el-button
              v-if="
                scope.row.orderStatus == 0 &&
                  meta.indexOf('CourseCancelPay') > -1
              "
              v-preventReClick
              type="text"
              @click="rowCancel(scope.row)"
            >取消支付</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />

    <el-dialog
      title="退款"
      :visible.sync="RefoundModal"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      width="800px"
    >
      <div>
        <div class="mb20">
          <span>退款类型：</span>
          <el-radio v-model="refundType" label="0">仅退款</el-radio>
          <el-radio v-model="refundType" label="1">退款退课</el-radio>
        </div>
        <el-table
          ref="RefoundTableRef"
          :data="RefoundInfo"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table mb30"
          @selection-change="RefoundSelectionChange"
        >
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column
            align="center"
            label="学员姓名"
            prop="studentName"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="课程价格"
            prop="coursePrice"
            min-width="80"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="数量"
            prop="num"
            min-width="60"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="实付款"
            prop="price"
            min-width="80"
            show-overflow-tooltip
          />
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="RefoundModal = false">取消</el-button>
        <el-button
          :loading="RefoundLoading"
          type="primary"
          @click="handleRefound"
        >确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="退款详情"
      :visible.sync="RefoundDetailModal"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      width="800px"
    >
      <div>
        <div class="mb20">
          <span>退款类型：</span>
          <span> {{ refundType === "0" ? "仅退款" : "退款退课" }} </span>
        </div>
        <el-table
          ref="RefoundTableRef"
          :data="selectedCourseList"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table mb30"
        >
          <el-table-column
            align="center"
            label="学员姓名"
            prop="studentName"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="课程价格"
            prop="coursePrice"
            min-width="80"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="数量"
            prop="num"
            min-width="60"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="实付款"
            prop="price"
            min-width="80"
            show-overflow-tooltip
          />
        </el-table>
        <div class="df_ac">
          <span>退款金额：</span>
          <el-input
            v-model="changePrice"
            :disabled="!isChangePrice"
            oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,2})?).*$/g, '$1');"
            type="text"
            class="w200 mr20"
          />
          <el-checkbox v-model="isChangePrice" class="mr20">改价</el-checkbox>
          <!-- <span class="ml20 placeholder9">注：线上支付的退款金额原路返回</span> -->
        </div>
        <div class="df_ac mt20">
          <span>退款原因：</span>
          <el-input v-model="remarkRefound" class="w400" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="RefoundDetailModal = false">取消</el-button>
        <el-button
          :loading="RefoundLoading"
          type="primary"
          @click="confirmRefound"
        >确定</el-button>
      </div>
    </el-dialog>
    <Detail ref="DetailRef" />
    <orderDialog ref="orderRef" @orderSuccess="getList()" />
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import store from '@/store'
import { courseOrderEx, courseOrderVenueList, getOrderTypeQuery, courseOrderCancel, courseRefund, refundCourse, allConfigList, courseOrderRefund, courseOrderRefundAc, printOrder } from '@/api'
import { queryFormConfig } from './config'
import QueryForm from '@/components/QueryForm'
import dayjs from 'dayjs'
import Detail from './detail.vue'
import orderDialog from '@/components/order'
export default {
  name: 'OfflinecoursesOrder',
  components: {
    QueryForm,
    Detail,
    orderDialog
  },
  data() {
    return {
      RefoundModal: false,
      RefoundLoading: false,
      RefoundDetailModal: false,
      isChangePrice: false,
      changePrice: 0,
      refundType: '1',
      activeOrderId: '',
      remarkRefound: '',
      RefoundInfo: [],
      selectedCourseList: [],

      modalDialog: store.getters.dialog,
      subLoading: false,
      queryFormConfig,
      meta: [],
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      filters: {},
      listLoading: true,
      show: false,
      orderId: '',
      allPayMethedList: [],
      form: {},
      rules: {
        price: [
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            required: true,
            message: '请输入正确课时总价(元),最多保留2位小数',
            trigger: 'blur'
          }
        ],
        info: [
          { required: true, message: '费用由线下退款，请具体描述退课原因', trigger: 'blue' }
        ],
        isAgree: [
          { required: true, message: '请选择财务是否同意', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.pdgj()
    let time = []
    const start = new Date()
    const end = new Date()
    start.setTime(end.getTime() - 3600 * 1000 * 24 * 29)
    time = [dayjs(start).format('YYYY-MM-DD'), dayjs(end).format('YYYY-MM-DD')]
    this.$set(this.filters, 'Times', time)
    this.getList(1)
    this.getOrderStatusList()
  },
  activated() {
    this.$refs.table.doLayout()
  },
  methods: {
    getOrderStatusList() {
      getOrderTypeQuery({ param: {}}).then(res => {
        this.queryFormConfig.formItems[2].options = res.recordList || []
      })
    },
    rowClickGoOn(row) {
      this.$refs.orderRef.continuePay(row, 'studentPay')
    },
    handleExport() {
      this.subLoading = true
      const { filters } = this
      const venueId = sessionStorage.getItem('venueId')
      filters.flag = '2'
      const param = { ...filters }
      if (filters.Times && filters.Times.length > 0) {
        filters.startTime = filters.Times[0]
        filters.endTime = filters.Times[1]
      } else {
        filters.startTime = null
        filters.endTime = null
      }
      courseOrderEx({ param: { venueId, ...filters }})
        .then((res) => {
          this.subLoading = false
          if (res.errorCode === '000000') {
            window.open(res.record.showUrl, '_blank')
          }
        })
        .catch(() => {
          this.subLoading = false
        })
    },
    getList(page) {
      this.listLoading = true
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      filters.flag = '2'
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      if (filters.Times && filters.Times.length > 0) {
        filters.startTime = filters.Times[0]
        filters.endTime = filters.Times[1]
      } else {
        filters.startTime = null
        filters.endTime = null
      }
      courseOrderVenueList({ pagination, param: { venueId, ...filters }})
        .then(res => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.total = res.totalCount
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    rowCancel(row) {
      this.$confirm('此操作将取消支付, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        courseOrderCancel({
          param: { orderId: row.orderId }
        }).then(res => {
          if (res.errorCode !== '000000') return
          this.$message.success('取消订单成功')
          this.getList()
        })
      })
    },
    handleDetail(row) {
      this.$refs.DetailRef.getOrderDetail(row)
      this.$refs.DetailRef.isShow = true
    },
    rowPrint(id) {
      this.$confirm('此操作将打印小票, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          printOrder({
            param: {
              contentMap: {},
              venueId: sessionStorage.getItem('venueId'),
              workId: id,
              templateCode: 'COURSETPML'
            }
          })
            .then((res) => {
              console.log(res)
            })
            .catch((err) => {
              console.log(err)
            })
        })
        .catch(() => {
          // this.$message.info('操作已取消')
        })
    },
    handleRefound() {
      const { refundType, selectedCourseList } = this
      if (selectedCourseList.length === 0) return this.$message.warning('请先选择需退款课程')
      const orderId = this.activeOrderId
      const detailIds = selectedCourseList.map(i => i.studentId)
      const param = {
        orderId,
        refundType,
        detailIds,
        type: '0'
      }
      this.RefoundLoading = true
      courseOrderRefundAc({ param }).then(res => {
        this.RefoundLoading = false
        if (res.errorCode !== '000000') return
        this.changePrice = res.record
        this.RefoundModal = false
        this.RefoundDetailModal = true
        this.remarkRefound = ''
      }, () => {
        this.RefoundLoading = false
      })
    },
    confirmRefound() {
      const { refundType, selectedCourseList, changePrice, remarkRefound, isChangePrice } = this
      const orderId = this.activeOrderId
      const detailIds = selectedCourseList.map(i => i.studentId)
      if (changePrice === '' || changePrice === null || changePrice === undefined) {
        return this.$message.warning('请输入退款金额')
      }
      const param = {
        orderId,
        refundType,
        detailIds,
        type: '1',
        refundPrice: changePrice,
        remark: remarkRefound,
        isChange: isChangePrice ? '1' : '0'
      }
      this.RefoundLoading = true
      courseOrderRefundAc({ param }).then(res => {
        this.RefoundLoading = false
        if (res.errorCode !== '000000') return
        this.RefoundDetailModal = false
        this.$message.success('退款成功')
        this.getList()
      }, () => {
        this.RefoundLoading = false
      })
    },
    rowClickRefound(row) {
      courseOrderRefund({ param: { orderId: row.orderId }}).then((res) => {
        this.RefoundInfo = res.recordList || []
      })
      this.activeOrderId = row.orderId
      this.RefoundModal = true
    },
    RefoundSelectionChange(val) {
      this.selectedCourseList = val
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    tke(e) {
      this.orderId = e.orderId
      this.show = true
    },
    tk(e) {
      const that = this
      this.$confirm('确认退款, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        courseRefund({ param: { orderId: e.orderId }})
          .then(res => {
            if (res.errorCode === '000000') {
              that.$message.success('退款成功')
              that.getList(1)
            }
          })
          .catch(() => {})
      })
    },
    pdgj() {
      allConfigList({ param: { type: '2', code: '1' }}).then(res => {
        if (res.errorCode === '000000') {
          this.allPayMethedList = res.recordList
          const arrb = res.recordList
          arrb.forEach(e => {
            e.label = e.name
          })
          this.queryFormConfig.formItems[4].options = arrb
        }
      }).catch(err => {
        console.log(err)
      })
    },
    nameWithPayMethod(payM) {
      const obj = this.allPayMethedList.find(item => item.value === payM)
      if (obj) {
        return obj.name
      } else {
        return '-'
      }
    },
    onSubmit() {
      const that = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const param = {}
          param.orderId = that.orderId
          param.money = Number(that.form.price)
          param.note = that.form.info
          param.isAgree = that.form.isAgree
          that.$confirm('是否确认退课?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            refundCourse({ param })
              .then((res) => {
                if (res.errorCode === '000000') {
                  that.show = false
                  that.$message.success('退课成功')
                  that.getList(1)
                }
              })
          })
            .catch(() => {
              // this.$message.info('已取消操作')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    clearList() {
      this.filters = {}
      this.getList(1)
    },
  }
}
</script>
